import requests
import os
import re
import time
import logging
import json
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(filename)s line:%(lineno)d %(levelname)s:%(message)s',
                    datefmt='%H:%M:%S',
                    )





class DyDld():
    def __init__(self):
        self.dypath = r"E:\mp4\婉瑜"
        self.sec_uid = "MS4wLjABAAAAShc4DTXJNodPjtkx56dpJY8NGaOSbAtVsLnCeT5tWIs"
        os.makedirs(self.dypath, exist_ok=True)
        
        self.count = 0
    def get_response(self, max_cursor=0):
        url="https://m.douyin.com/web/api/v2/aweme/post/?reflow_source=reflow_page&sec_uid=%s&count=21&max_cursor=%s" % (self.sec_uid, max_cursor)
        params = {}
        headers= {
                'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
                'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
                'pragma': 'no-cache',
                "cookie": '''ttwid=1%7C8piAcjJ7m9tFUgp5YgwXtbe1U10_kN6FeqlxPeRqNtQ%7C1668955719%7C68fb18e390c39f5edc30d9334e81e13ea8fd1be28da87f02cea4bbca5f6e4a1f; d_ticket=5489af8e1389685abf2b76badc7d5c9a5d4cb; n_mh=ngx4nTLueyUCiZv_idyOERZ5MXExBFl1qO_3KQQd_eI; passport_assist_user=CjxVOmrtTUYMWkCposaGMXnetsbPSWi8udgtUQJoEPSujPSW3bEyHYi7Cn1y_EyjtsKGVEYImDYbmx_9iwEaSAo8MNiEvTPnbpDk73PLKpjIEIo_6fGLgwj2F4RZhwWonUWUSRCLU73TSGEHukyMv9S6tug39VA1Rj-TkcuJELndoQ0Yia_WVCIBAxc0JSo%3D; sso_uid_tt=84f8ceea5e733f41c77967779b0d49f4; sso_uid_tt_ss=84f8ceea5e733f41c77967779b0d49f4; toutiao_sso_user=4a9c4e5976171842bcac14e6e7587164; toutiao_sso_user_ss=4a9c4e5976171842bcac14e6e7587164; odin_tt=685c0c7fe5c47732dba92a716e386afbdb8976c1cdf182abf1e2bb16a5c938c79565b9fc7d8761adec043ace5191effa; uid_tt=df45afd4f6c35512a8c06e62e304c08f; uid_tt_ss=df45afd4f6c35512a8c06e62e304c08f; sid_tt=5c11538b13e7a3425a315c47409960f8; sessionid=5c11538b13e7a3425a315c47409960f8; sessionid_ss=5c11538b13e7a3425a315c47409960f8; LOGIN_STATUS=1; passport_csrf_token=69890dbce404c46e09089c4b84c4eac6; passport_csrf_token_default=69890dbce404c46e09089c4b84c4eac6; store-region=cn-zj; store-region-src=uid; sid_ucp_sso_v1=1.0.0-KDQ2ZWVlYzhlYmFlMTBjYjEyODUxMDA0NzExMjY0YzhkMDA5NDVjOGUKHQjrkO2s4gIQtanUngYY7zEgDDDngJXVBTgCQPEHGgJsZiIgNGE5YzRlNTk3NjE3MTg0MmJjYWMxNGU2ZTc1ODcxNjQ; ssid_ucp_sso_v1=1.0.0-KDQ2ZWVlYzhlYmFlMTBjYjEyODUxMDA0NzExMjY0YzhkMDA5NDVjOGUKHQjrkO2s4gIQtanUngYY7zEgDDDngJXVBTgCQPEHGgJsZiIgNGE5YzRlNTk3NjE3MTg0MmJjYWMxNGU2ZTc1ODcxNjQ; sid_guard=5c11538b13e7a3425a315c47409960f8%7C1674908853%7C5184000%7CWed%2C+29-Mar-2023+12%3A27%3A33+GMT; sid_ucp_v1=1.0.0-KGJhMGNmYTBiZDhhMTgwZjZmN2E0NThhODM3MjJmYWE1MTNmODBlNTAKFwjrkO2s4gIQtanUngYY7zEgDDgCQPEHGgJsZiIgNWMxMTUzOGIxM2U3YTM0MjVhMzE1YzQ3NDA5OTYwZjg; ssid_ucp_v1=1.0.0-KGJhMGNmYTBiZDhhMTgwZjZmN2E0NThhODM3MjJmYWE1MTNmODBlNTAKFwjrkO2s4gIQtanUngYY7zEgDDgCQPEHGgJsZiIgNWMxMTUzOGIxM2U3YTM0MjVhMzE1YzQ3NDA5OTYwZjg; SEARCH_RESULT_LIST_TYPE=%22single%22; download_guide=%223%2F20230209%22; FOLLOW_NUMBER_YELLOW_POINT_INFO=%22MS4wLjABAAAA4Lh8weNPRBaGwyu7ZNLOk5SFWrfFZYKQGw4WDvPCADk%2F1676044800000%2F0%2F0%2F1675962060457%22; VIDEO_FILTER_MEMO_SELECT=%7B%22expireTime%22%3A1676566356878%2C%22type%22%3A1%7D; FOLLOW_LIVE_POINT_INFO=%22MS4wLjABAAAA4Lh8weNPRBaGwyu7ZNLOk5SFWrfFZYKQGw4WDvPCADk%2F1676044800000%2F0%2F0%2F1675962447318%22; strategyABtestKey=%221675961847.413%22; home_can_add_dy_2_desktop=%221%22; __ac_nonce=063e52620009fbedbb46e; __ac_signature=_02B4Z6wo00f01of65lgAAIDD5PAmMG8N7LKHyuLAAMIn63; s_v_web_id=verify_ldxcfq1o_3lLh1vaz_KmAb_4by3_99Dx_8l7NMkZc1uxe; ttcid=41294888ba394292aa368c682fa34f2829; msToken=INyFsM8Pl7iZKhgo7oubu40qiDVJDAbcbVgu73Z1s0ANkNNxl-YY7x3xlKgvA_h6wzZBaH-fk5ZneZijHN_STpK1JAq33Uyc6G5-Wt8e1w22eJCqc6VDmvhLp5SBARw=; msToken=jyaxPaEeT-Tj_znJvzIy2XTxLo22v6mas7zq29nq-uxe-QJL71f30BF0SYm8h_c7785fnzYBTFCRxOu8SqlMVs447xydImIYGUOBbkXw2lgWKS8Q4_H-Jcd-OBu_zMo=; tt_scid=hlJRTgfvIqv5Jkmry3k0y4TOGsAU-YZ55YOGJ4fWIvF0fIMYAmSa2TQcc3wt5vtGc45c''',
                'cache-control': 'no-cache',
                'Referrer Policy': 'strict-origin-when-cross-origin',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',
            }
        response = requests.get(url, params=params, headers=headers, timeout=10)

        jj = response.json()

        return jj

    def get_video_list(self, max_cursor):
        jj = self.get_response(max_cursor)
        if "max_cursor" not in jj:
            print(jj)
        max_cursor = jj["max_cursor"]
        min_cursor = jj["min_cursor"]
        aweme_list = jj["aweme_list"]
        has_more = jj["has_more"]
        nickname = None
        video_list = []
        for item in aweme_list:
            if nickname is None:
                nickname = item['author']['nickname'] if re.sub(r'[\/:*?"<>|]', '', item['author']['nickname']) else None
            title = re.sub(r'[\/:*?"<>|]', '', item['desc']) if item['desc'] else '无标题'
            video_url=item['video']['play_addr']['url_list'][0]
            video_url = video_url.replace('aweme.snssdk.com', 'api.amemv.com')
            video_list.append([title, video_url])
            aweme_id = item["aweme_id"]
        return has_more, max_cursor, video_list


    def write_file(self, title, content):
        dyfile = os.path.join(self.dypath, title)
        dymp4 = "%s.mp4" % dyfile
        while os.path.isfile(dymp4):
            self.count += 1
            dymp4 = "%s%s.mp4" % (dyfile, self.count)
        try:
            with open(dymp4, "wb") as fp:
                fp.write(content)
        except OSError:
            dymp4 = "%s.mp4" % self.count
            with open(dymp4, "wb") as fp:
                fp.write(content)

    def try_get_video_list(self, max_cursor):
        for  i in range(100):
            try:
                return self.get_video_list(max_cursor)
            except Exception as e:
                print(e)
                print("重试", max_cursor)
                time.sleep(5)

    def main(self):
        has_more = True
        max_cursor = 0
        while has_more:
            has_more, max_cursor, video_list = self.try_get_video_list(max_cursor)
            for title, url in video_list:
                content = requests.get(url).content
                logging.info((title, "下载完成"))
                self.write_file(title, content)



DyDld().main()